from rest_framework import serializers
from .models import BookInfo, HeroInfo


class BookInfoSerializers(serializers.ModelSerializer):
    """书籍序列化器"""

    class Meta:
        # 指明关联的模型类
        model = BookInfo
        # model = HeroInfo
        # 指明响应的字段
        fields = '__all__'  # 返回所有字段
        # fields = ('id', 'hname', 'hgender') # 返回括号中的这些数据
        # read_only_fields = ('id', 'bread', 'bcomment')  # 指定括号内的那些为
        # depth = 1  #  嵌套的层级数量
        extra_kwargs = {
            'bread':{'min_value':0, 'required':True},
            'bcomment':{'min_value':0, 'required':True}
        }


class BookRelatedField(serializers.RelatedField):
    """自定义处理图书字段"""
    def to_representation(self, value):
        return 'book: %d %s'%(value.id, value.btitle)

def about_python(value):
    if 'python' not in value.lower():
        raise serializers.ValidationError("图书中不包含python")
    return value

class BookInfoSerializer(serializers.Serializer):
    """图书数据序列化器"""
    id = serializers.IntegerField(label='ID', read_only=True)
    # btitle = serializers.CharField(label='名称', max_length=20, validators=[about_python])
    btitle = serializers.CharField(label='名称', max_length=20)

    bpub_date = serializers.DateField(label='发布日期', required=False)
    bread = serializers.IntegerField(label='阅读量', required=False)
    bcomment = serializers.IntegerField(label='评论量', required=False)
    image = serializers.ImageField(label='图片', required=False)
    # 固定写法 关联的那个表小写_set
    # heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    # def validate_btitle(self,value):
    #     if 'python' not in value.lower():
    #         raise serializers.ValidationError("图书中不包含python")
    #     return value

    # def validate(self, attrs):
    #     bread = attrs['bread']
    #     bcomment = attrs['bcomment']
    #     if bread < bcomment:
    #         raise serializers.ValidationError('阅读量小于评论量')
    #     return attrs

    def create(self, validated_data):
        """新建数据"""
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        # 括号后面那个值是默认值，如果没更新的话还是使用原来的值
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance




class HeroInfoSerializers(serializers.Serializer):
    """英雄数据序列化器"""
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    id = serializers.IntegerField(label='ID', read_only=True)
    hname = serializers.CharField(label='名字', max_length=20)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别')
    hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
    # hbook = serializers.StringRelatedField(label='图书',read_only=True)
    # hbook = serializers.SlugRelatedField(label='图书', read_only=True, slug_field='bpub_date')
    hbook = BookRelatedField(read_only=True)


